<template>
  <div class="container">
    <transition
      leave-active-class="login-active"
      @after-leave="afterLeave"
      >
      <div v-if="showLogin" class="login">
        <div class="login-top">
          登录
        </div>
        <div class="login-center clearfix">
          <div class="login-center-img"><img src="/images/name.png"></div>
          <div class="login-center-input">
            <input type="text" v-model="wxid" placeholder="请输入您的用户名" onfocus="this.placeholder=''" onblur="this.placeholder='请输入您的用户名'">
            <div class="login-center-input-text">用户名</div>
          </div>
        </div>
        <div class="login-center clearfix">
          <div class="login-center-img"><img src="/images/password.png"></div>
          <div class="login-center-input">
            <input type="password" v-model="password" placeholder="请输入您的密码" onfocus="this.placeholder=''" onblur="this.placeholder='请输入您的密码'">
            <div class="login-center-input-text">密码</div>
          </div>
        </div>

        <div class="login-button" @click="handleLogin">
          登录
        </div>
      </div>
    
    </transition>
    <transition
      :duration="5000"
      enter-active-class="sk-rotating-plane-active"
      leave-active-class="sk-rotating-plane-active"
      @after-leave="rotatAfterLeave"
      >
      <div v-if="showRotate" class="sk-rotating-plane"></div>
    </transition>
  </div>
</template>

<script>
import '../assets/css/login.less'
export default {
  data () {
    return {
      showLogin: true,
      showRotate: false,
      wxid: '',
      password: ''
    }
  },
  methods: {
    async handleLogin () {
      this.showLogin = false

      try {
        const { data } = await this.http.post('/login', {
          wxid: this.wxid,
          password: this.password
        })
  
        if (data.success) {
          // 保存用户信息到localStorage和全局状态
          localStorage.setItem('user', JSON.stringify(data.user))
          this.state.user = data.user

          console.log('登录成功:', data.user)
          this.$router.push('/chat')
        } else {
          alert(data.message || '登录失败')
          this.showRotate = false
          this.showLogin = true
        }
      } catch (e) {
        console.error('登录错误:', e)
        const errorMessage = e.response?.data?.message || '登录失败: ' + e.message
        alert(errorMessage)
        this.showRotate = false
        this.showLogin = true
      }
    },
    rotatAfterLeave () {
      this.showLogin = true
    },
    afterLeave () {
      this.showRotate = true
    }
  }
}
</script>

<style>

</style>